<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div.container {
            position: relative;
            height: 20px;
            width: 400px;
            border-radius: 20px;
            margin: 100px auto;
            background-color: red;
        }

        div.scrollbar {
            position: absolute;
            height: 40px;
            left: -20px;
            top: -10px;
            width: 40px;
            border-radius: 50%;
            background-color: green;
        }
    </style>
</head>

<body>
<div class="container">
    <div class="scrollbar"></div>
</div>
<script>
    var container = document.querySelector('.container');
    var scrollbar = document.querySelector('.scrollbar');
    // 计算容器的offsetLeft
    var _left = container.offsetLeft;
    // 边界判断
    var leftMin = -scrollbar.clientWidth / 2;
    var leftMax = container.clientWidth - scrollbar.clientWidth / 2;
    scrollbar.onmousedown = function () {
        document.onmousemove = function (e) {
            // 得到鼠标想对于容器container的左侧坐标
            var left = e.clientX - _left;
            left = Math.min(Math.max(leftMin, left), leftMax);
            scrollbar.style.left = left + 'px';
        }
        document.onmouseup = function () {
            this.onmousemove = null;
        }
    }
</script>
</body>

</html>
